package chapter_24.udp.upload;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * Created by Administrator
 * Created time 2018/8/10 13:18.
 * 案例:文件上传工具(服务端)
 */
public class UploadServer {

    public static void main(String[] args) {

        Thread server = new Thread(() -> {
            System.out.println("服务端程序运行...");

            try (// 创建一个 DatagramSocket 监听端口的客户端请求
                 DatagramSocket datagramSocket = new DatagramSocket(6666);
                 // 由文件输出流创建缓冲输出流
                 FileOutputStream fileOutputStream = new FileOutputStream("./src/chapter_24/udp/upload/server.png");
                 // 由 Socket 获得输出流,并创建缓冲输出流
                 BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream)
            ) {
                // 缓冲区
                byte[] bytes = new byte[1024];

                // 循环接收数据报包
                while (true) {
                    // 创建数据报包,同于接收数据
                    DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
                    // 接收数据报包
                    datagramSocket.receive(datagramPacket);
                    // 接收数据长度
                    int len = datagramPacket.getLength();

                    if (len == 3) {
                        // 获取结束标示
                        String flag = new String(bytes, 0, 3);
                        // 判断结束标示,如果是 bye 则结束接收
                        if (flag.equalsIgnoreCase("bye")) {
                            break;
                        }
                    }
                    // 写入数据到文件输出流
                    bufferedOutputStream.write(bytes, 0, len);
                }
                System.out.println("接收文件完成!");
            } catch (IOException e) {
                System.out.println("IOException");
            }
        });
        // 启动线程
        server.start();
    }
}
